<template>
  <Page title="批改结果">
    <template #navBarCustom>
      <div class="nav-bar-btns flex"></div>
    </template>
    <template #content>
      <div class="w-full h-full p-20px box-border">
        <div class="container w-full h-full bg-white flex overflow-hidden">
          <!-- 图片 -->
          <scroll-view ref="scroll-pictures" class="pictures w-p-50 h-full overflow-scroll">
            <div class="w-full flex flex-col justify-center">
              <el-image
                v-for="(picture, index) in correcter.pictures"
                :key="index"
                :src="picture"
                :preview-src-list="[picture]"
                fit="cover"
                style="vertical-align: top"
              />
            </div>
          </scroll-view>
          <!-- 评语 -->
          <scroll-view ref="scroll-comments" class="comments w-p-50 h-full overflow-scroll">
            <div class="w-full px-14px box-border">
              <!-- 分数 -->
              <div class="score flex items-center">
                <div class="module-item flex text-333 font-medium mt-20px mb-12px">
                  <div class="rect mr-6px"></div>
                  <div class="font-medium text-333">总分</div>
                </div>
                <div class="ml-8px">
                  <span class="text-30C9A1 font-semibold" style="font-size: 50px">{{
                    correcter.totalScore
                  }}</span>
                  <span class="text-30C9A1">分</span>
                </div>
              </div>
              <!-- 评语 -->
              <div class="comment-total">
                <div class="module-item flex text-333 font-medium mt-20px mb-12px">
                  <div class="rect mr-6px"></div>
                  <div class="font-medium text-333">总评语</div>
                </div>
                <div class="text font-normal text-444444">
                  <div>{{ correcter.totalComment }}</div>
                </div>
              </div>
              <!-- 分项评分+评语 -->
              <div class="comment-sub">
                <div class="module-item flex text-333 font-medium mt-20px mb-12px">
                  <div class="rect mr-6px"></div>
                  <div class="font-medium text-333">分项评分+评语</div>
                </div>
                <div class="items">
                  <div class="item">
                    <div class="title font-normal text-333"
                      ><span class="font-medium">主题：</span>
                      <span>{{ correcter.subComments.theme.score }}</span
                      >分</div
                    >
                    <div class="detail font-normal text-444444">{{
                      correcter.subComments.theme.comment
                    }}</div>
                  </div>
                  <div class="item">
                    <div class="title font-normal text-333"
                      ><span class="font-medium">内容：</span>
                      <span>{{ correcter.subComments.content.score }}</span
                      >分</div
                    >
                    <div class="detail font-normal text-444444">{{
                      correcter.subComments.content.comment
                    }}</div>
                  </div>
                  <div class="item">
                    <div class="title font-normal text-333"
                      ><span class="font-medium">结构：</span>
                      <span>{{ correcter.subComments.organization.score }}</span
                      >分</div
                    >
                    <div class="detail font-normal text-444444">{{
                      correcter.subComments.organization.comment
                    }}</div>
                  </div>
                  <div class="item">
                    <div class="title font-normal text-333"
                      ><span class="font-medium">表达：</span>
                      <span>{{ correcter.subComments.expression.score }}</span
                      >分</div
                    >
                    <div class="detail font-normal text-444444">{{
                      correcter.subComments.expression.comment
                    }}</div>
                  </div>
                </div>
              </div>
              <!-- 建议 -->
              <div class="suggestion">
                <div class="module-item flex text-333 font-medium mt-20px mb-12px">
                  <div class="rect mr-6px"></div>
                  <div class="font-medium text-333">建议</div>
                </div>
                <div class="text font-normal text-444444">
                  {{ correcter.totalSuggestion }}
                </div>
              </div>
              <!-- 其它 -->
              <div class="other text-30C9A1 py-14px">
                <!-- 错字 -->
                <div class="item text-FF4040">
                  <div class="title font-medium">错字：{{ correcter.misspelling.num }}个</div>
                  <div class="detail font-normal">
                    <div v-for="(detail, index) in correcter.misspelling.details" :key="index">
                      {{ `${index + 1}.${detail}` }}
                    </div>
                  </div>
                </div>
                <!-- 成语 -->
                <div class="item">
                  <div class="title font-medium">成语： {{ correcter.idiom.num }}个</div>
                  <div class="detail font-normal">{{ correcter.idiom.details.join('、') }}</div>
                </div>
                <!-- 引用 -->
                <div class="item">
                  <div class="title font-medium">引用： {{ correcter.quote.num }}个</div>
                  <div class="detail font-normal">
                    <div v-for="(detail, index) in correcter.quote.details" :key="index">
                      {{ `${index + 1}.${detail}` }}
                    </div>
                  </div>
                </div>
                <!-- 句评 -->
                <div class="item">
                  <div class="title font-medium">句评： {{ correcter.sentenceComment.num }}个</div>
                  <div class="detail font-normal">
                    <div v-for="(detail, index) in correcter.sentenceComment.details" :key="index">
                      {{ `${index + 1}.${detail}` }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </scroll-view>
        </div>
      </div>
    </template>
  </Page>
</template>

<script>
import Page from '@/components/page'
import ScrollView from '@/components/scroll-view'

export default {
  components: {
    Page,
    ScrollView
  },
  beforeRouteEnter(to, from, next) {
    next(async (vm) => {
      const { answer_base64, answer } = from.params

      vm.answer_base64 = answer_base64
      vm.answer = answer
      vm.correcter.init({ answer_base64, answer })
    })
  },
  data() {
    return {
      answer_base64: undefined, // 拍照上传的图片
      answer: undefined, // 好未来AI批改结果
      correcter: {
        vm: this._self,
        pictures: [], // 图片,
        totalScore: 0, // 总分
        totalComment: '', // 总评
        subComments: {
          theme: {
            score: 0,
            comment: ''
          }, // 主题
          content: {
            score: 0,
            comment: ''
          }, // 内容
          organization: {
            score: 0,
            comment: ''
          }, // 结构
          expression: {
            score: 0,
            comment: ''
          } // 表达
        }, // 分项评分+评语
        totalSuggestion: '', // 建议
        misspelling: {
          num: 0, // 个数
          details: [] // 错字数组
        }, // 错字
        idiom: {
          num: 0, // 个数
          details: [] // 成语数组
        }, // 成语
        quote: {
          num: 0, // 个数
          details: [] // 引用数组
        }, // 引用
        sentenceComment: {
          num: 0, // 个数
          details: [] // 句评数组
        }, // 句评
        init: function (props) {
          const { answer_base64, answer } = props

          // 检查数据
          if (
            !(Array.isArray(answer_base64) && answer_base64.length > 0) ||
            typeof answer != 'object'
          ) {
            this.vm.$message.error('格式错误')
            return
          }

          // 初始化
          const loading = this.vm.$loading({
            lock: true,
            text: '加载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.5)'
          })
          // 一分钟内提交不成功关闭loading弹窗
          const timer = setTimeout(() => {
            loading.close()
          }, 60000)

          try {
            // 下划线坐标
            const drawLineLocations = {
              misspelling: [],
              idiom: [],
              quote: [],
              sentenceComment: []
            }

            // 1.批改详情
            const {
              original_essay_info, // object 原始作文信息
              overall_result, // object 综合结果
              features_result, // object 特征结果
              gec_result, // object 批改结果
              writing_highlight, // object 写作亮点
              article_neatness, // object 书写工整度
              path_id // string 路径id
            } = answer

            // original_essay_info
            const {
              original_paragraph_list, // array 包含段落的数组
              original_paragraph_location,
              original_sentence_list, // array 每个句子的分段和分句信息
              font_size, // array	平均字宽, 平均字高(只有两个元素,单位px)
              page_font_size, // array 每页平均字体大小
              page_rotate, // array 对应每页的旋转角度,不旋转则都为0;旋转角度为[0, 90, 180, 270]中的一个
              answer_title, // string	识别到的标题
              path_id: original_essay_info_path_id // string 路径id
            } = original_essay_info

            // overall_result
            const {
              total_score, // int	学生总得分(百分制)
              total_comment, // string 作文综合评语
              total_suggestion, // string	作文综合建议
              category_score, // object 各个维度得分
              paragraph_comment // 段评
            } = overall_result
            const { theme, content, organization, expression } = category_score

            // 总分、总评、分项评分+评语、建议
            {
              this.totalScore = total_score
              this.totalComment = total_comment
              this.subComments.theme = theme
              this.subComments.content = content
              this.subComments.organization = organization
              this.subComments.expression = expression
              this.totalSuggestion = total_suggestion
            }

            // gec_result
            const {
              theme_info, //object 文题相关性信息
              grammar_mistake_info, //object 拼写错误信息
              grammar_sentence_mistake_info // object 病句信息
            } = gec_result

            // 错字
            {
              const { info } = grammar_mistake_info
              info.forEach((item) => {
                const { details } = item
                details.forEach((detail) => {
                  this.misspelling.details.push(`${detail.origin}→${detail.corrected}`)
                  this.misspelling.num += 1
                  drawLineLocations.misspelling.push({
                    page: detail.page,
                    location: detail.location
                  })
                })
              })
            }

            // writing_highlight
            const {
              idiom, // object 成语引用详细信息
              allegorical, // object 俗语引用详细信息
              quote, // object 佳句引用详细信息
              rhetorical, // object 修辞句信息
              description // object 描写句信息
            } = writing_highlight

            // 成语
            {
              const { num, info } = idiom
              this.idiom.num = num
              info.forEach((item) => {
                const { details } = item
                details.forEach((detail) => {
                  this.idiom.details.push(detail.content)
                  detail.location_info.forEach((idiomItem) => {
                    drawLineLocations.idiom.push(idiomItem)
                  })
                })
              })
            }

            // 俗语引用
            {
              const { num, info } = allegorical
              this.quote.num += num
              info.forEach((item) => {
                const { details } = item
                details.forEach((detail) => {
                  this.quote.details.push(detail.content)
                  detail.location_info.forEach((allegoricalItem) => {
                    drawLineLocations.quote.push(allegoricalItem)
                  })
                })
              })
            }

            // 佳句引用
            {
              const { num, info } = quote
              this.quote.num += num
              info.forEach((item) => {
                const { details } = item
                details.forEach((detail) => {
                  this.quote.details.push(detail.content)
                  detail.location_info.forEach((quoteItem) => {
                    drawLineLocations.quote.push(quoteItem)
                  })
                })
              })
            }

            // 句评-修辞句
            {
              const { num, info } = rhetorical
              this.sentenceComment.num += num
              for (let key in info) {
                if (key != 'path_id' && Array.isArray(info[key]) && info[key].length > 0) {
                  const details = info[key]
                  details.forEach((detail) => {
                    const sentenceComment = detail.sentence_comment
                    sentenceComment
                      ? this.sentenceComment.details.push(sentenceComment)
                      : this.sentenceComment.details.push('（无）')
                    detail.location_info.forEach((sentenceCommentItem) => {
                      drawLineLocations.sentenceComment.push(sentenceCommentItem)
                    })
                  })
                }
              }
            }

            // 句评-描写句
            {
              const { num, info } = description
              this.sentenceComment.num += num
              for (let key in info) {
                if (key != 'path_id' && Array.isArray(info[key]) && info[key].length > 0) {
                  const details = info[key]
                  details.forEach((detail) => {
                    const sentenceComment = detail.sentence_comment
                    sentenceComment
                      ? this.sentenceComment.details.push(sentenceComment)
                      : this.sentenceComment.details.push('（无）')
                    detail.location_info.forEach((sentenceCommentItem) => {
                      drawLineLocations.sentenceComment.push(sentenceCommentItem)
                    })
                  })
                }
              }
            }

            // 2.图片
            const renderTasks = []
            const renderImage = (imageSrc, pageIndex = 1) => {
              return new Promise((resolve) => {
                const canvas = document.createElement('canvas')
                const ctx = canvas.getContext('2d')
                const img = new Image()
                img.crossOrigin = 'anonymous'
                const regex = /data:image\/[\w\W]+?base64/gi
                img.src = regex.test(imageSrc) ? imageSrc : `${imageSrc}?timestamp=${Date.now()}`
                img.onload = function () {
                  const { width, height } = img
                  canvas.width = width
                  canvas.height = height
                  ctx.drawImage(img, 0, 0, width, height) // 底图
                  // 1.错字
                  drawLineLocations.misspelling.forEach((item) => {
                    const { page, location } = item

                    if (pageIndex === page) {
                      const [
                        center, // 中心点
                        left_top, // 左上
                        right_top, // 右上
                        right_bottom, // 右下
                        left_bottom // 左下
                      ] = location
                      const startCoordinate = left_bottom
                      const endCoordinate = right_bottom
                      const lineWidth = page_font_size[pageIndex - 1].h / 10

                      ctx.moveTo(startCoordinate.x, startCoordinate.y) // 起点
                      ctx.lineTo(endCoordinate.x, endCoordinate.y) // 终点
                      ctx.lineWidth = lineWidth // 线宽
                      ctx.strokeStyle = '#51c3ff' // 线样式
                      ctx.stroke() // 绘制
                    }
                  })
                  // 2.成语
                  drawLineLocations.idiom.forEach((item) => {
                    const { page, location } = item

                    if (pageIndex === page) {
                      const startCoordinate = location[0]
                      const endCoordinate = location[location.length - 1]
                      const lineWidth = page_font_size[pageIndex - 1].h / 10

                      ctx.moveTo(startCoordinate.x, startCoordinate.y) // 起点
                      ctx.lineTo(endCoordinate.x, endCoordinate.y) // 终点
                      ctx.lineWidth = lineWidth // 线宽
                      ctx.strokeStyle = '#51c3ff' // 线样式
                      ctx.stroke() // 绘制
                    }
                  })
                  // 3.引用
                  drawLineLocations.quote.forEach((item) => {
                    const { page, location } = item

                    if (pageIndex === page) {
                      const startCoordinate = location[0]
                      const endCoordinate = location[location.length - 1]
                      const lineWidth = page_font_size[pageIndex - 1].h / 10

                      ctx.moveTo(startCoordinate.x, startCoordinate.y) // 起点
                      ctx.lineTo(endCoordinate.x, endCoordinate.y) // 终点
                      ctx.lineWidth = lineWidth // 线宽
                      ctx.strokeStyle = '#51c3ff' // 线样式
                      ctx.stroke() // 绘制
                    }
                  })
                  // 4.句评
                  drawLineLocations.sentenceComment.forEach((item) => {
                    const { page, location } = item

                    if (pageIndex === page) {
                      const startCoordinate = location[0]
                      const endCoordinate = location[location.length - 1]
                      const lineWidth = page_font_size[pageIndex - 1].h / 10

                      ctx.moveTo(startCoordinate.x, startCoordinate.y) // 起点
                      ctx.lineTo(endCoordinate.x, endCoordinate.y) // 终点
                      ctx.lineWidth = lineWidth // 线宽
                      ctx.strokeStyle = '#51c3ff' // 线样式
                      ctx.stroke() // 绘制
                    }
                  })

                  resolve(canvas.toDataURL('image/png'))
                }
              })
            }
            answer_base64.forEach((picture, pageIndex) =>
              renderTasks.push(renderImage(picture, pageIndex + 1))
            )
            Promise.all(renderTasks)
              .then((pictures) => {
                this.pictures = pictures
              })
              .finally(() => {
                clearTimeout(timer)
                loading.close()
              })
          } catch (error) {
            this.reset()
            clearTimeout(timer)
            loading.close()
            this.vm.$message.error('格式错误')
          }
        },
        reset: function () {
          this.pictures.length = 0
          this.totalScore = 0
          this.totalComment = ''
          this.subComments.theme = {
            score: 0,
            comment: ''
          }
          this.subComments.content = {
            score: 0,
            comment: ''
          }
          this.subComments.organization = {
            score: 0,
            comment: ''
          }
          this.subComments.expression = {
            score: 0,
            comment: ''
          }
          this.totalSuggestion = ''
          this.misspelling = {
            num: 0,
            details: []
          }
          this.idiom = {
            num: 0,
            details: []
          }
          this.quote = {
            num: 0,
            details: []
          }
          this.sentenceComment = {
            num: 0,
            details: []
          }
        }
      }
    }
  },
  computed: {},
  created() {},
  methods: {}
}
</script>

<style lang="scss" scoped>
.container {
  border-radius: 16px;

  .pictures {
  }

  .comments {
    .module-item {
      font-size: 26px;
      line-height: 26px;

      .rect {
        width: 6px;
        height: 26px;
        background: linear-gradient(180deg, #51c3ff 0%, #31b3f7 100%);
        border-radius: 3px;
      }
    }

    .score {
      font-size: 26px;
    }

    .comment-total {
      .text {
        font-size: 16px;
      }
    }

    .comment-sub {
      .items {
        .item {
          &:not(:first-child) {
            margin-top: 6px;
          }

          .title {
            font-size: 18px;
          }

          span:not(:nth-child(1)) {
            color: #51c3ff;
          }

          .detail {
            font-size: 16px;
          }
        }
      }
    }

    .suggestion {
      .text {
        font-size: 16px;
      }
    }

    .other {
      .item {
        &:not(:first-child) {
          margin-top: 6px;
        }

        .title {
          font-size: 20px;
        }

        .detail {
          font-size: 16px;
        }
      }
    }
  }
}
</style>
